package com.doone.telmarket.domain.service.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.springframework.stereotype.Service;

import com.doone.telmarket.domain.SiteResource;
import com.doone.telmarket.domain.service.SitePageGenerative;

/**
 * 
 * @author 吴同庆
 * @date 2009-9-21
 * @description 站点页面生成接口实现类
 * @package     com.doone.telmarket.domain.service
 */
@Service("sitePageGenerative")
public class SitePageGenerate implements SitePageGenerative{
	
	private String charsetName = "UTF-8";
	
	public String getCharsetName() {
		return charsetName;
	}
	
	
	public void generatePage(String rootPath,String pagePath,SiteResource siteResource) throws IOException{
		String dirPath = rootPath.concat(siteResource.getPath());
		makeDirs(dirPath);
		String destPath = rootPath.concat(siteResource.getFullPath());
		writePage(pagePath,destPath);
	}
	
	
	

	void makeDirs(String dirPath){
		File file = new File(dirPath);
		if(!file.exists())
		{
			file.mkdirs();
		}
	}
	
	
	
	void writePage(String pagePath, String destPath) throws IOException {
		URL url = new URL(pagePath);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.connect();
		InputStream inputStream = connection.getInputStream();
		BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destPath),
				getCharsetName()));
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, getCharsetName()));
		String line;

		while ((line = bufferedReader.readLine()) != null) {
			if (line.trim().length() > 0) {
				bufferedWriter.write(line);
				bufferedWriter.newLine();
			}
		}
		bufferedWriter.close();
		bufferedReader.close();
	}
	

}
